﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;
using SdmxMl.Helper;
using SdmxMl.Panels;
using SdmxMl.Common;
using SdmxMl.Structure;
using SdmxMl.GenericMetadata;
using SdmxMl.Manager;
using SdmxMl.Report;

namespace SdmxMl.UC
{
    /// <summary>
    /// Tabbed control for editimg Metadataset generic item
    /// </summary>
    public partial class UcAttributeValueSet : UserControl, IUrnSelect
    {
        #region Internal Members

        private PanelAnnotationList pannelAnnot;
        private BindingManagerBase bm = null;
        private ReportedAttributeType _reportedAttribute;
        private ReportStructureType r;
        private TreeNode rootNode;
        private TreeNavigation treeNavigate;
        private bool _isFinal;
        private DataTable table;
        private bool inBinding;
        private MetadataSetType _metadataSet;
        private MetadataStructureDefinitionType _msd;
        private WorldHtmlAttribute wdh;
        private HtmlAttributesReport htmlReport;
        private TreeNode nodeTarget;

        private AttributeValueSetType _attributeValueSet;

        #endregion //Internal Members

        #region Construction

        public UcAttributeValueSet()
        {
            InitializeComponent();
            toolStripComboBoxEditType.SelectedIndex = 0;
            treeNavigate = new TreeNavigation();
            treeNavigate.TreeSdmx = treeViewH;
            treeNavigate.RecordNavButtons(toolStripButtonPrevSel, toolStripButtonNextSelection, toolStripButtonNavParent, toolStripComboBoxHistory);

            StringBuilder sb = new StringBuilder();
            //sb.Append("<html><head><link rel=\"stylesheet\" href=\"http://ec.europa.eu/eurostat/ramon/stylesheets/ramon.css\" type=\"text/css\" media=\"screen\">");
            sb.Append("<html><head>");
            sb.Append("<STYLE>body {  font-size:9pt; font-family:Arial }</STYLE>");
            sb.Append("</head><body></body></html>");
            webBrowserReport.DocumentText = sb.ToString();

            webBrowserReport.Navigating += new WebBrowserNavigatingEventHandler(webBrowserReport_Navigating);
        }

        void webBrowserReport_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            try
            {

                e.Cancel = true;
                if (e.Url != null)
                    System.Diagnostics.Process.Start(e.Url.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion // Construction

        #region Binding

        public bool BindFromNode(TreeNode node, PanelAnnotationList panelAnnotation, bool isFinal)
        {
            _isFinal = isFinal;
            pannelAnnot = panelAnnotation;
            _attributeValueSet = null;
            _metadataSet = null;
            _msd = null;
            _cvt = null;

            nodeTarget = null;
            if (node != null)
            {
                _attributeValueSet = node.Tag as AttributeValueSetType;
                nodeTarget = node;
            }

            BindToControls();

            return this.Visible;
        }

        public bool UpdateNodeTag(TreeNode node)
        {
            bool err = false;
            if (node != null)
            {
                err = BindFromControls();
                if (_attributeValueSet != null && node.Text != _attributeValueSet.ToString())
                    node.Text = _attributeValueSet.ToString();
            }

            return false; // true on error
        }

        private void BindToControls()
        {
            treeViewH.BeginUpdate();
            treeViewH.Nodes.Clear();
            table = null;
            inBinding = true;

            if (_attributeValueSet != null)
            {
                Visible = true;
                IsFinalEditControls(_isFinal);

                _metadataSet = _attributeValueSet.ParentMetadataSet;

                _msd = ReferenceManager.LocateMetadataStructureDefinition(_metadataSet.MetadataStructureRef);

                // Target tab, fill target identifiers combo
                comboBoxTargetRef.Items.Clear();
                if (_msd != null)
                {
                    // Propose target identifiers and partial list
                    comboBoxTargetRef.Items.Add(_msd.TargetIdentifiers.FullTargetIdentifier.Id);
                    foreach (PartialTargetIdentifierType pti in _msd.TargetIdentifiers.PartialTargetIdentifierList)
                        comboBoxTargetRef.Items.Add(pti.Id);

                    if (_attributeValueSet.TargetRef == null || _attributeValueSet.TargetRef.Length == 0)
                        _attributeValueSet.TargetRef = _msd.TargetIdentifiers.FullTargetIdentifier.Id;
                }
                comboBoxTargetRef.Text = _attributeValueSet.TargetRef;



                table = _attributeValueSet.TargetValuesTypeList.AsDataTable();
                dataGridViewInfo.DataSource = table;

                // Get Report reference
                r = ReferenceManager.LocateReportStructure(_metadataSet.MetadataStructureRef, _metadataSet.ReportRef);

                // Meta attributes tab
                rootNode = new TreeNode(_attributeValueSet.TargetRef);
                rootNode.Tag = _attributeValueSet;
                ConstructTreeHierarchy(_reportedAttribute);

                tabControl_SelectedIndexChanged(this, EventArgs.Empty);
                //   UpdateAnnotation();
                IsFinalEditControls(_isFinal);

                inBinding = false;
                dataGridViewInfo_SelectionChanged(this, EventArgs.Empty);


            }
            else
                Visible = false;
            treeViewH.EndUpdate();

        }


        // Manage Edition possibility
        private void IsFinalEditControls(bool isFinal)
        {
            bool enabled = isFinal == false;

            // Target Tab
            comboBoxTargetRef.Enabled = enabled;

            // Meta Attrib Values
            ucAttributeEditControlTarget.IsFinal = isFinal;
            ucAttributeEditControl.IsFinal = isFinal;

            // ToolStrip Bar
            toolStripButtonDelCodeRef.Enabled = enabled && _msd != null;
            toolStripButtonNewCode.Enabled = enabled && _msd != null; ;
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateAnnotation();
            if (tabControl.SelectedTab == tabPageReportHtml)
            {
                htmlReport = new HtmlAttributesReport(_msd);
                webBrowserReport.Document.Body.InnerHtml = htmlReport.MakeReport(_attributeValueSet, r, checkBoxReportFull.Checked, true);
                //    webBrowserReport.Document.ExecCommand("SelectAll", false, "null");
                //    webBrowserReport.Document.ExecCommand("FontName", false, "Arial");
                //    webBrowserReport.Document.ExecCommand("Unselect", false, "null");
            }
            else if (tabControl.SelectedTab == tabPageRtf)
            {
                wdh = new WorldHtmlAttribute(_msd);
                richTextBoxReport.Rtf = wdh.MakeRtfReport(_attributeValueSet, r, checkBoxReportFull.Checked, true);
            }
            else if (tabControl.SelectedTab == tabPageMetaAttrib)
            {
                if (treeViewH != null && treeViewH.SelectedNode != null)
                {
                    ReportedAttributeType repa = treeViewH.SelectedNode.Tag as ReportedAttributeType;
                    if (repa != null)
                        pannelAnnot.BindFromNode(repa, _isFinal);
                }
            }
        }

        private void UpdateAnnotation()
        {
            if (tabControl.SelectedIndex != 1)
                pannelAnnot.BindFromNode(null, _isFinal);
        }

        protected bool BindFromControls()
        {
            bool err = false;

            RefreshFromEdition();

            if (_attributeValueSet != null)
            {
                // Force update on selected row
                dataGridViewInfo_SelectionChanged(this, EventArgs.Empty);

                // Target page
                _attributeValueSet.TargetRef = comboBoxTargetRef.Text;

                dataGridViewInfo.EndEdit();
                inBinding = true;
                table.AcceptChanges();
                for (int i = 0; i < table.Rows.Count; ++i)
                    _attributeValueSet.TargetValuesTypeList[i].Value = table.Rows[i]["Value"].ToString();
                inBinding = false;

                // Reported Meta Attributes
                _attributeValueSet.ReportedAttributeList.Clear();
                UpdateRefList(rootNode, _attributeValueSet.ReportedAttributeList);



            }
            return err;
        }

        // recursive helper
        private void UpdateRefList(TreeNode parentNode, ReportedAttributeTypeList rList)
        {
            foreach (TreeNode node in parentNode.Nodes)
            {
                ReportedAttributeType crt = node.Tag as ReportedAttributeType;
                rList.Add(crt);
                crt.ReportedAttributeList.Clear();
                UpdateRefList(node, crt.ReportedAttributeList);

            }
        }

        #endregion //Binding

        #region Tree Events

        /// <summary>Constructs Hierarchy of Reported attributes </summary>
        /// <param name="nodeTagToSelect"> Previous attribute selected in tree or null</param>
        private void ConstructTreeHierarchy(object nodeTagToSelect)
        {
            treeViewH.DrawMode = TreeViewDrawMode.Normal;
            treeViewH.BeginUpdate();
            rootNode.Nodes.Clear();
            treeViewH.Nodes.Clear();
            _attributeValueSet.ReportedAttributeList.GetTreeHierarchyAsNodes(rootNode);

            treeViewH.Nodes.Add(rootNode);
            rootNode.Expand();

            UpdateTreeIcons(rootNode);

            treeViewH.EndUpdate();

            SelectMemorizedTarget(nodeTagToSelect);

            treeNavigate.Reset();
            treeViewH.DrawMode = TreeViewDrawMode.OwnerDrawText;

        }

        /// <summary>
        /// Try to retrieve a previously selected reported attribute
        /// </summary>
        /// <param name="nodeTagToSelect"></param>
        private void SelectMemorizedTarget(object nodeTagToSelect)
        {
            TreeNode targetNode = null;
            string targetText = nodeTagToSelect != null ? nodeTagToSelect.ToString() : string.Empty;
            if (treeViewH.Nodes.Count > 0)
                TreeHelper.LocateText(treeViewH.Nodes[0], targetText, ref targetNode);
            if (targetNode != null)
            {
                treeViewH.SelectedNode = targetNode;
                treeViewH.SelectedNode.EnsureVisible();
            }
            else
            {
                if (rootNode.Nodes.Count > 0)
                {
                    treeViewH.SelectedNode = rootNode.Nodes[0];
                    treeViewH.SelectedNode.EnsureVisible();
                }
            }
        }

        /// <summary>
        /// Refresh tree nodes text according to current language
        /// </summary>
        /// <param name="node"></param>
        private void TreeViewUpdateLang(TreeNode node)
        {
            if (node.Tag != null)
                node.Text = node.Tag.ToString();

            foreach (TreeNode n in node.Nodes)
                TreeViewUpdateLang(n);
        }

        private void UpdateTreeIcons(TreeNode node)
        {
            ReportedAttributeType repa = node.Tag as ReportedAttributeType;
            UpdateNodeIcon(node, repa);
            foreach (TreeNode nd in node.Nodes)
                UpdateTreeIcons(nd);
        }

        private void UpdateNodeIcon(TreeNode node, ReportedAttributeType repa)
        {
            if (node == rootNode)
                node.ImageKey = node.SelectedImageKey = "dirTree";
            else
            {
                MetadataAttributeType meta = repa != null && r != null ?
                    r.MetadataAttributeList.GetAttributeReferingConcept(repa.ConceptID) : null;
                SetReportedIcon(meta, node);
            }
        }

        private void SetReportedIcon(MetadataAttributeType meta, TreeNode node)
        {
            ReportedAttributeType repa = node.Tag as ReportedAttributeType;
            if (repa != null)
            {

                if (meta != null && meta.UsageStatus == UsageStatusType.Mandatory)
                {
                    if (repa.AnnotationList.Count == 0)
                        node.ImageKey = node.SelectedImageKey = "requiredInfo";
                    else
                        node.ImageKey = node.SelectedImageKey = "CLIP07.ico"; // note attached
                }
                else
                {
                    if (repa.AnnotationList.Count == 0)
                        node.ImageKey = node.SelectedImageKey = "optionalInfo";
                    else
                        node.ImageKey = node.SelectedImageKey = "CLIP07blue.ico"; // note attached
                }
            }
            else
                node.ImageKey = node.SelectedImageKey = "noInfo";
        }

        // Retrieve updated code info
        private void treeViewH_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            RefreshFromEdition();
        }

        /// <summary>
        /// When leaving edited item, be sure to fetch edited content
        /// </summary>
        private void RefreshFromEdition()
        {
            TreeNode nd = treeViewH.SelectedNode;
            if (nd != null)
            {
                ReportedAttributeType repa = nd.Tag as ReportedAttributeType;
                UpdateNodeIcon(nd, repa);
                if (repa != null && ucAttributeValueHtml1.Visible)
                    repa.Value.UpdateForCurrentLanguage(ucAttributeValueHtml1.Content);
            }
        }

        private void treeViewH_AfterSelect(object sender, TreeViewEventArgs e)
        {
            UpdateControlsFromTreeSelected();
            DisplayInfo(TreeHelper.CalculateNodeChilds(treeViewH.SelectedNode));
        }

        // Info in status bar
        public void DisplayInfo(string msg)
        {
            if (msg != null)
                labelStatusInfo.Text = msg;
        }

        /// <summary> Update detail view of selected attribute </summary>
        private void UpdateControlsFromTreeSelected()
        {
            try
            {
                _reportedAttribute = null;

                textBoxConceptName.Text = string.Empty;
                richTextBoxContextInfo.Text = string.Empty;

                if (treeViewH.SelectedNode != null)
                {
                    groupBoxMetaAttrib.Visible = true;
                    groupBoxReferedConcept.Visible = true;
                    _reportedAttribute = treeViewH.SelectedNode.Tag as ReportedAttributeType;
                    if (_reportedAttribute != null)
                    {
                        if (r != null)
                        {
                            ConceptType c = null;
                            FlatHierarchicalList flatList = null;
                            MetadataAttributeType meta = r.MetadataAttributeList.GetAttributeReferingConcept(_reportedAttribute.ConceptID);
                            TextFormatType tft = null;
                            bool isMultiCodes = false;
                            bool isPresentational = false;
                            if (meta != null)
                            {
                                ISdmxArtefactRef codelistRef = meta.RepresentationInfo;
                                if (codelistRef != null)
                                {
                                    CodeListType clt = ReferenceManager.LocateCodelist(codelistRef);
                                    if (clt != null)
                                        flatList = clt.CodeList;
                                }

                                tft = meta.TextFormat;
                                isMultiCodes = meta.MetaOccurence.IsMultiCodes;
                                isPresentational = meta.MetaOccurence.IsPresentational;

                                ConceptSchemeType cst = ReferenceManager.LocateConceptScheme(meta.ConceptSchemeInfo);
                                c = ReferenceManager.LocateConcept(cst, _reportedAttribute.ConceptID);
                                if (c != null)
                                {
                                    textBoxConceptName.Text = c.Name.ToString();
                                    richTextBoxContextInfo.Text = c.ContextInfo;
                                }
                            }

                            ucAttributeEditControl.BindReferedConcept(c, flatList, tft, isMultiCodes, isPresentational);
                            ucAttributeEditControl.MetaDataValue = _reportedAttribute;
                            ucAttributeValueHtml1.MetaDataValue = _reportedAttribute;
                        }
                    }
                }
                if (_reportedAttribute == null)
                {
                    groupBoxReferedConcept.Visible = false;
                    groupBoxMetaAttrib.Visible = false;
                }

                pannelAnnot.BindFromNode(_reportedAttribute, _isFinal);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "MSD", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        #endregion // Tree Events

        #region ToolStripHierarchy

        private void toolStripButtonNewCode_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Inserts all missing Attributes?", "Check",
               MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                treeViewH.BeginUpdate();
                rootNode.Nodes.Clear();
                r.MetadataAttributeList.CreateReferedAttributesTreeHierarchy(rootNode, _attributeValueSet.ReportedAttributeList);
                rootNode.Expand();
                UpdateTreeIcons(rootNode);
                treeViewH.EndUpdate();

                SelectMemorizedTarget(_reportedAttribute);
            }
        }

        private void toolStripButtonDelCodeRef_Click(object sender, EventArgs e)
        {
            if (r != null)
            {
                if (MessageBox.Show("Removes All unused optional Attributes?", "Check",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    treeViewH.BeginUpdate();

                    RemoveUnused(rootNode);

                    treeViewH.EndUpdate();
                }
            }
        }

        // recursive helper
        private void RemoveUnused(TreeNode parentNode)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            foreach (TreeNode node in parentNode.Nodes)
            {
                ReportedAttributeType repa = node.Tag as ReportedAttributeType;
                MetadataAttributeType meta = null;
                if (repa != null)
                {
                    meta = r.MetadataAttributeList.GetAttributeReferingConcept(repa.ConceptID);
                    if (meta != null && meta.UsageStatus == UsageStatusType.Conditional)
                        if (repa.IsFilled() == false)
                            listNodes.Add(node);
                }

                if (repa == null || meta == null)
                {
                    // Reported is no more defined in report, remove
                    listNodes.Add(node);
                }
            }

            foreach (TreeNode ndRemove in listNodes)
                parentNode.Nodes.Remove(ndRemove);

            foreach (TreeNode node in parentNode.Nodes)
                RemoveUnused(node);
        }


        private void toolStripButtonExpandCollapse_Click(object sender, EventArgs e)
        {
            if (treeViewH.SelectedNode != null)
            {   // update meta
                treeViewH_BeforeSelect(this, null);

                TreeHelper.toolStripButtonExpandCollapse(treeViewH);
                // Update as event locked
                treeViewH_AfterSelect(this, new TreeViewEventArgs(treeViewH.SelectedNode));

            }

        }


        #endregion // ToolStripHierarchy

        #region Search in Reported Attributes Values

        private void toolStripButtonSearchAttrib_Click(object sender, EventArgs e)
        {
            try
            {
                if (_metadataSet != null && _reportedAttribute != null)
                {
                    DlgSearchReportedAttrib aDlg = new DlgSearchReportedAttrib(_metadataSet, _reportedAttribute);

                    aDlg.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        #endregion //

        #region Navigation

        private void buttonNavigateConcept_Click(object sender, EventArgs e)
        {
            if (_reportedAttribute != null && r != null)
            {
                MetadataAttributeType meta = r.MetadataAttributeList.GetAttributeReferingConcept(_reportedAttribute.ConceptID);
                if (meta != null)
                {
                    ConceptSchemeType cst = ReferenceManager.LocateConceptScheme(meta.ConceptSchemeInfo);
                    if (cst == null)
                    {
                        object ob = NavigationManager.LocateNavigateWithRegistry(SdmxArtefactType.Concepts,
                            meta.ConceptSchemeInfo.FullIdent, true, false, null);
                        cst = ReferenceManager.LocateConceptScheme(meta.ConceptSchemeInfo);
                    }

                    ConceptType c = ReferenceManager.LocateConcept(cst, _reportedAttribute.ConceptID);
                    NavigationManager.RequestNavigation(c);
                }
            }
        }
        #endregion // Navigation

        #region DatagridViewTarget (Identifier Components)

        private ComponentValueType _cvt;
        private int _index;

        private void dataGridViewInfo_SelectionChanged(object sender, EventArgs e)
        {
            if (inBinding)
            {
                _cvt = null;
                _index = 0;
                return;
            }

            bm = dataGridViewInfo.BindingContext[dataGridViewInfo.DataSource, dataGridViewInfo.DataMember];
            if (bm.Count > 0)
            {
                DataRow findRow = ((DataRowView)bm.Current).Row;
                if (findRow != null)
                {
                    // Update previous if needed
                    if (_cvt != null)
                        table.Rows[_index]["Value"] = _cvt.Value;

                    IHierarchyManage flatList = null;
                    _index = (dataGridViewInfo.DataSource as DataTable).Rows.IndexOf(findRow);
                    _cvt = _attributeValueSet.TargetValuesTypeList[_index];

                    // Get MSD Identifier component of selected target key
                    if (_msd != null && _metadataSet != null && _cvt != null)
                    {
                        string component = _cvt.Component;

                        IdentifierComponentType ict = _msd.TargetIdentifiers.FullTargetIdentifier.IdentifierComponentList.LocateIdentifier(component);
                        if (ict != null)
                        {
                            ISdmxArtefactRef iref = ict.RepresentationScheme;
                            flatList = ReferenceManager.ListFromIdentifierComponent(ict);
                        }
                    }

                    // Set specialized control to edit key value acording to its defined representation
                    ucAttributeEditControlTarget.BindReferedConcept(null, flatList, null, false, false);
                    ucAttributeEditControlTarget.MetaDataValue = _cvt;

                }
            }
        }
        #endregion

        #region Menu bar events

        private void buttonWorld_Click(object sender, EventArgs e)
        {
            try
            {
                if (wdh != null)
                    wdh.CallRtfEditor();

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkBoxReportFull_CheckedChanged(object sender, EventArgs e)
        {
            tabControl_SelectedIndexChanged(this, EventArgs.Empty);

        }

        private void richTextBoxReport_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(e.LinkText);

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Report Link Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// Provides a persistence of HTML document Tab
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void toolStripButPrintHtml_Click(object sender, EventArgs e)
        {
            try
            {
                if (webBrowserReport != null && webBrowserReport.Document != null &&
                    webBrowserReport.Document.Body.InnerHtml != null)
                {
                    saveFileDialog.Filter = "HTML files|*.htm|All Files|*.*";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName, false, Encoding.Default))
                        {
                            sw.Write(webBrowserReport.Document.Body.InnerHtml);
                        }

                        System.Diagnostics.Process.Start(saveFileDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        #endregion

        #region IUrnSelect Members

        public void SelectItem(UrnParser up)
        {
            if (treeViewH != null && _attributeValueSet != null && _metadataSet != null)
            {
                string[] arr = up.SubTypeId.Split('.');
                if (up.SubType == "ReportedAttributeType" && arr.Length > 1 && arr[0] == _metadataSet.ReportRef)
                {
                    TreeNode targetNode = null;
                    if (treeViewH.Nodes.Count > 0)
                        TreeHelper.LocateText(treeViewH.Nodes[0], arr[arr.Length - 1], ref targetNode);
                    if (targetNode != null)
                    {
                        treeViewH.SelectedNode = targetNode;
                        treeViewH.SelectedNode.EnsureVisible();
                        tabControl.SelectedIndex = 1;
                    }
                }
            }
        }

        #endregion

        private void WebBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            ArtefactRefTyped art = null;

            UrnParser p = new UrnParser(e.Url.ToString());
            if (p.IsSupported)
            {
                art = new ArtefactRefTyped(p.ArType, p.ArtefactId, p.AgencyId, p.Version);
                // If already in memory, navigate otherwhile get from regidtry
                if (NavigationManager.LocatenavigateProject(SdmxArtefactType.Concepts, art.FullIdent, p) == null)
                    NavigationManager.NavigateWithRegistry(SdmxArtefactType.Concepts, art.FullIdent, true, p);

                e.Cancel = true;
            }
        }

        #region Edit mode selection Event

        /// <summary>
        /// Event for Selection of edit mode
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void toolStripComboBoxEditType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (toolStripComboBoxEditType.SelectedIndex == 1)
            {
                ucAttributeValueHtml1.Visible = true;
                ucAttributeEditControl.Visible = false;
            }
            else
            {
                ucAttributeValueHtml1.Visible = false;
                ucAttributeEditControl.Visible = true;
            }
        }
        #endregion

        private void toolStripButtonAddRepeatable_Click(object sender, EventArgs e)
        {
            try
            {
                ReportedAttributeType repa = treeViewH != null && treeViewH.SelectedNode != null ?
                    treeViewH.SelectedNode.Tag as ReportedAttributeType : null;
                if (repa != null && r != null)
                {
                    MetadataAttributeType meta = r.MetadataAttributeList.GetAttributeReferingConcept(repa.ConceptID);
                    int maxi = meta.MetaOccurence.MaxUnspecified ? int.MaxValue : meta.MetaOccurence.MaxOccurs;
                    if (maxi > 1 && CountExisting(treeViewH.SelectedNode, repa) < maxi)
                    {
                        ReportedAttributeType rat = new ReportedAttributeType();
                        rat.ConceptID = repa.ConceptID;
                        TreeNode ndRoot = new TreeNode(rat.ConceptID);
                        ndRoot.Tag = rat;
                        SetReportedIcon(meta, ndRoot);

                        CreateReferedAttributesTreeHierarchy(ndRoot, meta, _attributeValueSet.ReportedAttributeList);
                        TreeNodeCollection nodes = treeViewH.SelectedNode.Parent == null ? treeViewH.Nodes : treeViewH.SelectedNode.Parent.Nodes;
                        nodes.Insert(treeViewH.SelectedNode.Index + 1, ndRoot);
                        treeViewH.SelectedNode = ndRoot;

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "MSD", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CreateReferedAttributesTreeHierarchy(TreeNode parentNode, MetadataAttributeType meta, ReportedAttributeTypeList reportedList)
        {
            ReportedAttributeType ratParent = parentNode.Tag as ReportedAttributeType;
            ReportedAttributeType rat = null;
            foreach (MetadataAttributeType crt in meta.MetadataAttributeList)
            {
                string conceptId = crt.ConceptInfo.Id;
                rat = new ReportedAttributeType();
                rat.ConceptID = conceptId;
                ratParent.ReportedAttributeList.Add(rat);

                TreeNode nd = new TreeNode(conceptId);
                nd.Tag = rat;
                parentNode.Nodes.Add(nd);
                SetReportedIcon(crt, nd);
                CreateReferedAttributesTreeHierarchy(nd, crt, reportedList);
            }
        }

        private int CountExisting(TreeNode ndCurrent, ReportedAttributeType repa)
        {
            int count = 0;
            TreeNodeCollection nodes = ndCurrent.Parent == null ? treeViewH.Nodes : ndCurrent.Parent.Nodes;
            foreach (TreeNode nd in nodes)
            {
                ReportedAttributeType rat = nd.Tag as ReportedAttributeType;
                if (rat != null && rat.ConceptID == repa.ConceptID)
                    ++count;
            }
            return count;
        }

        private void toolStripButtonRemoveRepeatable_Click(object sender, EventArgs e)
        {
            try
            {
                ReportedAttributeType repa = treeViewH != null && treeViewH.SelectedNode != null ?
                    treeViewH.SelectedNode.Tag as ReportedAttributeType : null;
                if (repa != null && r != null)
                {
                    MetadataAttributeType meta = r.MetadataAttributeList.GetAttributeReferingConcept(repa.ConceptID);
                    int mini = meta.MetaOccurence.MinUnspecified ? 1 : meta.MetaOccurence.MinOccurs;
                    int currentCount = CountExisting(treeViewH.SelectedNode, repa);
                    if (currentCount > mini)
                    {
                        treeViewH.SelectedNode.Remove();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "MSD", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
    }
}
